package com.ruoyi.product.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.model.v2.ErrorCode;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.MqConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;

import com.ruoyi.eam.api.RemoteEamService;
import com.ruoyi.eam.api.domain.EamLocation;
import com.ruoyi.product.domain.WorkPlan;
import com.ruoyi.product.service.IPlanService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController
@RequestMapping("/plan")
public class PlanController extends BaseController {


    @Autowired
    private RemoteEamService remoteEamService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IPlanService planService;

    @PostMapping
    public AjaxResult add(@Validated @RequestBody WorkPlan plan) {
        Long cellId = plan.getCellId();
        String planCode = plan.getPlanCode();

        int isExist = planService.existPlan(planCode);

        if (isExist > 0) {
            throw new ServiceException("已存在的计划，不能添加相同的计划!", ErrorCode.INVALID_DATA_ID.getCode());
        }

        R<EamLocation> result = remoteEamService.getEamLocationById(cellId);

        if (result.getCode() == Constants.FAIL) {
            throw new ServiceException(result.getMsg(), Constants.FAIL);
        }

        EamLocation eamLocation = result.getData();
        plan.setCellName(eamLocation.getLocationName());
        plan.setCellCode(eamLocation.getLocationCode());
        //保存数据
        planService.addPlan(plan);

        //发送数据至MQ
        rabbitTemplate.convertAndSend(MqConstants.PLAN_EXCHANGE, MqConstants.ADD_PLAN_ROUTING_KEY, JSON.toJSONString(plan));

        return success();

    }
}
